package com.sl.au.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.AfterSaleTicket;
import com.sl.au.entity.ContractInfoView;
import com.sl.au.entity.ExdeContractPrudctP;
import com.sl.au.entity.Option;
import com.sl.au.entity.User;
import com.sl.au.repository.ExdeContractViewRepository;
import com.sl.au.service.ContractViewService;
import com.sl.au.service.QueryService;

@Service("ExdeContractViewService")
@Transactional
public class ExdeContractViewServiceImpl extends BaseServiceImpl implements ContractViewService {

	@Autowired
	ExdeContractViewRepository exdeContractViewRepository;
	
	@Autowired
	QueryService queryService;
	
	@Override
	public ExdeContractViewRepository getExdeContractViewRepository() {
		return this.exdeContractViewRepository;
	}

	@Override
	public List<Option> getSaleArea() {
		return this.exdeContractViewRepository.getSaleArea();
	}

	@Override
	public List<ContractInfoView> getContractInfos(int start, int length, Map<String, Object> condition, User user, String orderName, String dir) {
		@SuppressWarnings("unchecked")
		HashMap<String, Object>numMap=(HashMap<String, Object>)condition.get("numMap");
		Map<String,Object>namedParamsMap=new HashMap<String,Object>();
		StringBuilder hql=queryService.buildCombinedQueryHql("ContractInfoView",null, condition, namedParamsMap,null, user);
		for(String key:numMap.keySet()){
			Object value=numMap.get(key);
			if(key=="totalSum"){
				String[] a = value.toString().split(",");
				hql.append(" and ( 1<>1 ");
				for(int i=0;i<a.length;i++){
					if(a[i].equals("100万以下")) hql.append(" or (e.totalSum < 1000000  )");
					if(a[i].equals("100～500万")) hql.append(" or (e.totalSum >= 1000000 and e.totalSum<5000000 )");
					if(a[i].equals("500～1000万")) hql.append(" or (e.totalSum >= 5000000 and e.totalSum<10000000 )");
					if(a[i].equals("1000万以上")) hql.append(" or (e.totalSum >= 10000000  )");
				}
				hql.append(") "); 
			}else if(key=="cProductProcess"){
				String[] a = value.toString().split(",");
				hql.append(" and ( 1<>1 ");
				for(int i=0;i<a.length;i++){
					if(a[i].equals("未排产")) hql.append(" or (e.nTotalCount is null)");
					if(a[i].equals("已排产")) hql.append(" or (e.nTotalCount > 0 and e.nRKCount <> e.nTotalCount and e.nFinishCount <> e.nTotalCount )");
					if(a[i].equals("已入库")) hql.append(" or (e.nTotalCount > 0 and e.nRKCount > 0 and e.nRKCount = e.nTotalCount )");
					if(a[i].equals("已发运")) hql.append(" or (e.nFinishCount > 0 and e.nTotalCount > 0 and e.nTotalCount = e.nFinishCount )");
				}
				hql.append(") ");
			}else if(key=="Contract"){
				hql.append(" and (e.supplierCode like '%" + value.toString() + "%' )");
			/*}else if(key=="industryInfo"){
				if(value.toString().equals("无"))
					hql.append(" and (e.industryInfo='' )");
				else
					hql.append("and (e.industryInfo in ("+value.toString()+"))");*/
			} else{
				if (value instanceof String){
					 if(StringUtils.hasText((String)value)){
						 hql.append("and (e."+key+" in ("+value.toString()+"))");
					 }
				}
			}
		}
		String dataFilter=condition.get("dataFilter").toString();
		if(StringUtils.hasText(dataFilter)){
			//this.contractDataFilter(hql, dataFilter, user);
		}else{
			//return null;
		}
		hql.append(" order by " + orderName + " " + dir);
		Query query=queryService.createQueryHql(hql.toString());
		query.setFirstResult(start).setMaxResults(length);
		return queryService.executeHql(query, namedParamsMap);
			
	}
	
	/**数据过滤  
	 * @param hql
	 * @param dataFilter
	 * @param user
	 */
	private void contractDataFilter(StringBuilder hql, String dataFilter, User user){
		if(dataFilter.equals("本部门")){
			hql.append("and (e.superior='"+user.getSaleArea().getSuperior()+"')")
				.append("and (e.userId='"+user.getId()+"'")
				.append("or (e.auditState='审批中' or e.auditState='已提交' or e.auditState='通过'))");
		}else if(dataFilter.equals("本片区")){
			hql.append("and (e.superior='"+user.getSaleArea().getSuperior()+"'")
			.append("and e.areaName='"+user.getSaleArea().getAreaName()+"')")
			.append("and (e.userId='"+user.getId()+"'")
			.append("or (e.auditState='审批中' or e.auditState='已提交' or e.auditState='通过'))");
//			.append("and (e.auditState!='未提交') and (e.auditState!='驳回')");
//			.append("or (e.userId!='"+user.getId()+"' and e.auditState!='未提交' and e.auditState!='驳回')");
		}else if(dataFilter.equals("本人")){
			hql.append("and (e.userId='"+user.getId()+"')");
		}else if(dataFilter.equals("所有")){
//			hql.append("and (e.userId='"+user.getId()+"')")
//			.append("or (e.userId!='"+user.getId()+"' and e.auditState!='未提交' and e.auditState!='驳回')");
		}
	}

	@Override
	public List<ContractInfoView> getBeijianView(int start, int length, String contractViewId,
			String contractViewType) {
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		List<ContractInfoView> list = exdeContractViewRepository.getBeiViewById(contractViewId, contractViewType, pageable);
		return list;
	}

	@Override
	public long getBeijianViewCount(String contractViewId, String contractViewType) {
		long count = exdeContractViewRepository.getBeijianViewCount(contractViewId, contractViewType);
		return count;
	}

	@Override
	public List<AfterSaleTicket> getAfterSaleTicket(int start, int length, Map<String, String> condition,
			String orderName, String dir) {
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "id");
		List<AfterSaleTicket> list = exdeContractViewRepository.getAfterSaleTicket(condition.get("contractViewId"), pageable);
		return list;
	}
	
	@Override
	public long getAfterSaleTicketCount( Map<String, String> condition) {
		long count = exdeContractViewRepository.getAfterSaleTicketCount(condition.get("contractViewId"));
		return count;
	}

	@Override
	public List<ExdeContractPrudctP> getSpeed(String supplierCode) {
		return exdeContractViewRepository.getSpeed(supplierCode);
	}

	@Override
	public Double getContractSum(Map<String, Object> condition, User user, String orderName, String dir) {
		@SuppressWarnings("unchecked")
		HashMap<String, Object>numMap=(HashMap<String, Object>)condition.get("numMap");
		Map<String,Object>namedParamsMap=new HashMap<String,Object>();
		StringBuilder hql=queryService.buildCombinedQueryHql("ContractInfoView","sum(e.totalSum)", condition, namedParamsMap,null, user);
		for(String key:numMap.keySet()){
			Object value=numMap.get(key);
			if(key=="totalSum"){
				String[] a = value.toString().split(",");
				hql.append(" and ( 1<>1 ");
				for(int i=0;i<a.length;i++){
					if(a[i].equals("100万以下")) hql.append(" or (e.totalSum < 1000000  )");
					if(a[i].equals("100～500万")) hql.append(" or (e.totalSum >= 1000000 and e.totalSum<5000000 )");
					if(a[i].equals("500～1000万")) hql.append(" or (e.totalSum >= 5000000 and e.totalSum<10000000 )");
					if(a[i].equals("1000万以上")) hql.append(" or (e.totalSum >= 10000000  )");
				}
				hql.append(") "); 
			}else if(key=="cProductProcess"){
				String[] a = value.toString().split(",");
				hql.append(" and ( 1<>1 ");
				for(int i=0;i<a.length;i++){
					if(a[i].equals("未排产")) hql.append(" or (e.nTotalCount is null)");
					if(a[i].equals("已排产")) hql.append(" or (e.nTotalCount > 0 and e.nRKCount <> e.nTotalCount and e.nFinishCount <> e.nTotalCount )");
					if(a[i].equals("已入库")) hql.append(" or (e.nTotalCount > 0 and e.nRKCount > 0 and e.nRKCount = e.nTotalCount )");
					if(a[i].equals("已发运")) hql.append(" or (e.nFinishCount > 0 and e.nTotalCount > 0 and e.nTotalCount = e.nFinishCount )");
				}
				hql.append(") ");
			}else if(key=="Contract"){
				hql.append(" and (e.supplierCode like '%" + value.toString() + "%' )");
			} else{
				if (value instanceof String){
					 if(StringUtils.hasText((String)value)){
						 hql.append("and (e."+key+" in ("+value.toString()+"))");
					 }
				}
			}
		}
		String dataFilter=condition.get("dataFilter").toString();
		if(StringUtils.hasText(dataFilter)){
			//this.contractDataFilter(hql, dataFilter, user);
		}else{
			//return null;
		}
		//hql.append(" order by " + orderName + " " + dir);
		Query query=queryService.createQueryHql(hql.toString());
		System.out.println(hql.toString());
		if (null != query && null != namedParamsMap) {
			queryService.setNamedParams(query, namedParamsMap);
		}
		Double d = (Double)query.getSingleResult();
		return d;
		//return null;
	}

}
